import { HttpClient,HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { Task } from '../../pages/home/task';


@Injectable()
export class HttpDateProvider {

  private readonly baseUrl:string='https://api2.bmob.cn/1';
  private readonly httpOptions:object={
    headers:new HttpHeaders({
      'X-Bmob-Application-Id': '5cd3550c01687325ae7e2166b1216540',
      'X-Bmob-REST-API-Key': 'fa40033cd7122fad7e502b9ffa1c18d9',
      'Content-Type': 'application/json'
    })
  }

  constructor(public http: HttpClient) {
    console.log('获取HTTP数据服务加载');
  }

  /**
   * 获取待办事项列表
   * @returns {Observable<Task[]>} 待办事项列表集合
   */
  getTaskList():Observable<Task[]>{
    return this.http.get<Task[]>(`${this.baseUrl}/classes/ToDoList`,this.httpOptions).map(data=>data["results"]);
  }

  /**
   * 更新指定待办事项
   * @param task 
   */
  updateTask(task:Task):Observable<Task>{
    let _task={title:task.title,status:task.status,description:task.description};
    return this.http.put<Task>(`${this.baseUrl}/classes/ToDoList/${task.objectId}`,_task,this.httpOptions);
  }

  /**
   * 
   * @param task 删除指定待办事项
   */
  deleteTask(task:Task):Observable<{}>{
    return this.http.delete(`${this.baseUrl}/classes/ToDoList/${task.objectId}`,this.httpOptions)
  }

  /**
   * 新增待办事项
   * @param task 
   */
  addTask(task:Task):Observable<Task>{
    let _task={title:task.title,status:task.status,description:task.description};
    return this.http.post<Task>(`${this.baseUrl}/classes/ToDoList/`,_task,this.httpOptions);
  }

  /**
   * 获取指定待办事项
   * @param objectId 
   */
  getTask(objectId:string):Observable<Task>{
    return this.http.get<Task>(`${this.baseUrl}/classes/ToDoList/${objectId}`,this.httpOptions);
  }

}
